import jwt_decode from 'jwt-decode'
import dayjs from 'dayjs'
import { useUserStore } from './user'

export const useLoginStore = defineStore('login', () => {
  let userStore = useUserStore()
  let token = $ref('')
  let uid = $ref('')
  let roleId = $ref('')
  let isBack = $ref(false) //是否返回上一个页面
  // watch(() => token, () => {
  //   userStore.useGetInfoData()
  // })

  const isLogin = $computed(() => {
    if (isNilOrEmpty(token)) return false
    const decoded: any = jwt_decode(token)
    //console.log(decoded, 'decoded++++++')

    return dayjs().isBefore(dayjs.unix(decoded.exp))
  })

  const isOficialUser = $computed(() => {
    if (isNilOrEmpty(roleId)) return false
    return true
  })
  function setToken(payload: string) {
    token = payload
    userStore.useGetInfoData()
  }
  function setUid(payload: string) {
    uid = payload
  }
  function setRoleId(payload: string) {
    roleId = payload
  }
  function setIsBack(payload: any) {
    isBack = payload
  }
  function clearToken() {
    token = ''
  }

  async function isGoLogin() {
    if (!isOficialUser) {
      uni.navigateTo({
        url: '/pages/testlogin',
      })
      return
    }
    console.log('非正式用户')

  }

  function getToken() {
    //  get token from weixin
  }

  return {
    token: $$(token),
    uid: $$(uid),
    roleId: $$(roleId),
    isLogin: $$(isLogin),
    isBack: $$(isBack),
    getToken,
    setUid,
    setRoleId,
    setIsBack,
    setToken,
    clearToken,
    isGoLogin,
  }
}, { unistorage: { key: 'config-login' } })

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useLoginStore, import.meta.hot))
